package com.example.sj12.ui.home;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
//import androidx.appcompat.widget.SearchView;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;

import com.example.sj12.Data;
import com.example.sj12.DataAdapter;
import com.example.sj12.IntroduceActivity;
import com.example.sj12.LoginActivity;
import com.example.sj12.R;
import com.example.sj12.UserDao;
import com.example.sj12.upload;

import java.util.LinkedList;
import java.util.List;

public class HomeFragment extends Fragment {
    private Button btn;
    private ListView list,list1;//列表视图对象
    private SearchView s;
    private HomeFragment mContext;//设备上下文
    private List<Data> mData = null;//定义数据列表
    private HomeViewModel homeViewModel;
    int k;

    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        homeViewModel =
                ViewModelProviders.of(this).get(HomeViewModel.class);
        View root = inflater.inflate(R.layout.fragment_home, container, false);
        final String username = getActivity().getIntent().getStringExtra("username");//需要将数据传递到UserFragment中显示，第一种是直接在Fragment中获取Activity实例然后获取传递的Intent对象，如下
        final String url = getActivity().getIntent().getStringExtra("url");
        list = root.findViewById(R.id.lv);//初始化列表视图对象
        list1 = root.findViewById(R.id.lv1);//初始化列表视图对象
        s = root.findViewById(R.id.sv);//初始化列表视图对象
        mContext = HomeFragment.this;//初始化设备上下文
        getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);//安卓进入页面避免软键盘弹出的解决办法
        btn = root.findViewById(R.id.btn);
        btn.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), upload.class);
                intent.putExtra("username",username);
                Bundle bundle = new Bundle();
                bundle.putInt("picnumber", k);
                System.out.println("K值2为："+k);
                intent.putExtras(bundle);
                startActivity(intent);

            }

        });
        new Thread() {
            @Override
            public void run() {
                super.run();
                // 耗时操作
                UserDao u = new UserDao();
                Data picnumber=u.GetPicnumber(username);
                if(picnumber.getPicnumber()==1){
                    k=2;
                }
                else
                    k=picnumber.getPicnumber()+1;
                System.out.println("K值为："+k);
                UserDao d = new UserDao();
                mData = new LinkedList<>();//创建数据链表
                mData = d.searchHouse(username);//给数据链表增加内容
                //Log.i(TAG,"fun");
                //====================
                Handler mHandler = new Handler(Looper.getMainLooper()) {

                    @Override
                    public void handleMessage(@NonNull Message msg) {
                        super.handleMessage(msg);
                        // 切换到主线程
                        //一开始显示
                        list1.setVisibility(View.VISIBLE);
                        DataAdapter mAdapter = new DataAdapter((LinkedList<Data>) mData, mContext);//初始化适配器对象
                        list1.setAdapter(mAdapter);//设置适配器
                        list1.setOnItemClickListener(new AdapterView.OnItemClickListener(){

                            //listview点击事件
                            @Override
                            public void onItemClick(AdapterView<?> parent, View view,
                                                    int position, long id) {
                                // TODO Auto-generated method stub
                                //List<Data> list1=new ArrayList<Data>();

                                Data info = mData.get(position);
                                //List<Data>list1=new ArrayList<Data>();
                                Bundle bundle = new Bundle();

                                bundle.putString("name", info.getName());
                                //System.out.println("测试1"+info.getName());
                                bundle.putString("housename", info.getHousename());
                                //System.out.println("测试2"+info.getHousename());
                                bundle.putString("username", username);
                                bundle.putString("url", url);
                                //bundle.putInt("picnumber", k);

                                //bundle.putString("toWhere", info.getToWhere());
                                //bundle.putString("time",info.getTime());
                                //bundle.putString("content", info.getContent());

                                Intent intent = new Intent(getContext(), IntroduceActivity.class);
                                intent.putExtras(bundle);
                                //finish();
                                startActivity(intent);
                            }
                        });

                    }
                };
                mHandler.sendEmptyMessage(0);

            }
        }.start();
        //listview启动过滤
        list.setTextFilterEnabled(true);
        //一开始不显示
        list.setVisibility(View.GONE);
        //搜索框不自动缩小为一个搜索图标，而是match_parent
        s.setIconifiedByDefault(false);
        //显示搜索按钮
        s.setSubmitButtonEnabled(true);
        //默认提示文本
        s.setQueryHint("查找");
        s.setOnQueryTextListener(new SearchView.OnQueryTextListener()

        {
            //单击搜索按钮的监听
            @Override
            public boolean onQueryTextSubmit (final String query){
                new Thread() {
                    @Override
                    public void run() {
                        super.run();
                        // 耗时操作
                        UserDao d = new UserDao();
                        mData = new LinkedList<>();//创建数据链表
                        mData = d.getDate(query);//给数据链表增加内容
                        //Log.i(TAG,"fun");
                        System.out.println(mData.size());
                        //====================
                        Handler mHandler = new Handler(Looper.getMainLooper()) {

                            @Override
                            public void handleMessage(@NonNull Message msg) {
                                super.handleMessage(msg);
                                // 切换到主线程
                                DataAdapter mAdapter = new DataAdapter((LinkedList<Data>) mData, mContext);//初始化适配器对象
                                list.setAdapter(mAdapter);//设置适配器
                                list.setOnItemClickListener(new AdapterView.OnItemClickListener(){

                                    @Override
                                    public void onItemClick(AdapterView<?> parent, View view,
                                                            int position, long id) {
                                        // TODO Auto-generated method stub
                                        //List<Data> list1=new ArrayList<Data>();

                                        Data info = mData.get(position);
                                        //List<Data>list1=new ArrayList<Data>();
                                        Bundle bundle = new Bundle();

                                        bundle.putString("name", info.getName());
                                        bundle.putString("housename", info.getHousename());
                                        bundle.putString("username", username);
                                        bundle.putString("url", url);
                                        //bundle.putString("toWhere", info.getToWhere());
                                        //bundle.putString("time",info.getTime());
                                        //bundle.putString("content", info.getContent());

                                        Intent intent = new Intent(getContext(), IntroduceActivity.class);
                                        intent.putExtras(bundle);
                                        //finish();
                                        startActivity(intent);
                                    }
                                });
                            }
                        };
                        mHandler.sendEmptyMessage(0);

                    }
                }.start();
                Toast.makeText(getContext(), "123", Toast.LENGTH_SHORT).show();

                return false;
            }
            //输入字符的监听
            @Override
            public boolean onQueryTextChange (String newText){
                if (TextUtils.isEmpty(newText)) {
                    list.setVisibility(View.GONE);
                    list.clearTextFilter();// 清除ListView的过滤
                } else {
                    //mAdapter.getFilter().filter(newText);//通过适配器过滤
                    list.setVisibility(View.VISIBLE);
                    list.setFilterText(newText);// 使用用户输入的内容对ListView的列表项进行过滤
                    list.dispatchDisplayHint(View.INVISIBLE);//隐藏弹出的黑框
                }

                return true;
            }
        });
        /*final TextView textView = root.findViewById(R.id.text_home);
        homeViewModel.getText().observe(getViewLifecycleOwner(), new Observer<String>() {
            @Override
            public void onChanged(@Nullable String s) {
                textView.setText(s);
            }
        });*/
        return root;
    }
}
